﻿Imports System.Web
Imports System.Web.Services
Imports MongoDB.Driver
Imports MongoDB.Driver.Builders

Public Class FacebookHandler
    Implements System.Web.IHttpHandler
    Implements System.Web.SessionState.IRequiresSessionState

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim strAccessToken As String = ""
        Dim fcClient As Facebook.FacebookClient = Nothing
        Dim objFacebookUser As Object = Nothing
        Dim uCurrentUser As Trebuchet.User = Nothing

        Try

            'get the Access Token from the request and and save in session
            strAccessToken = context.Request("accessToken")
            context.Session("AccessToken") = strAccessToken

            fcClient = New Facebook.FacebookClient(strAccessToken)
            objFacebookUser = fcClient.Get("me")

            'Check for existing users
            If CheckForExistingUser(objFacebookUser, uCurrentUser) Then

                'Update our database with updated data from facebook
                UpdateUserFromFacebook(objFacebookUser)

            Else
                'If none exist, create a new user
                CreateUserFromFacebook(objFacebookUser, uCurrentUser)

            End If

            'If user was found or created, log in
            context.Session("user_id") = uCurrentUser._id
            context.Session("email") = uCurrentUser.Email

            If Not context.Session("user_id") Is Nothing Then

                'redirect user to dashboard
                context.Response.Redirect("Dashboard.aspx")

            Else

                'redirect to home page

            End If


        Catch ex As Exception

        End Try

    End Sub

    Private Function CheckForExistingUser(ByVal objFacebookUser As Object, ByRef uCurrentUser As Trebuchet.User) As Boolean

        Dim bolUserExists As Boolean = False
        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcUsers As MongoCollection(Of Trebuchet.User) = Nothing
        Dim mcUserCursor As MongoCursor = Nothing
        Dim uUser As Trebuchet.User = Nothing

        Try

            mdDatabase = DBHelper.GetDataBase()
            mcUsers = mdDatabase.GetCollection(Of Trebuchet.User)("Users")

            'get all users that match the username and are active
            mcUserCursor = mcUsers.FindAs(Of Trebuchet.User)(Query.And(Query.EQ("FacebookID", objFacebookUser.id.ToString), Query.EQ("Active", True)))

            If Not mcUserCursor Is Nothing Then

                For Each uUser In mcUserCursor

                    bolUserExists = True

                    uCurrentUser = uUser

                Next

            Else

                'No users found with this ID
                bolUserExists = False

            End If

        Catch ex As Exception

        Finally

            mdDatabase = Nothing
            mcUsers = Nothing
            mcUserCursor = Nothing
            uUser = Nothing

            CheckForExistingUser = bolUserExists

        End Try

    End Function

    Private Function CreateUserFromFacebook(ByVal objFacebookUser As Object, ByRef uNewUser As Trebuchet.User) As Boolean

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcUsers As MongoCollection(Of Trebuchet.User) = Nothing
        Dim mcUserCursor As MongoCursor = Nothing
        Dim uUser As Trebuchet.User = Nothing

        Try

            mdDatabase = DBHelper.GetDataBase()
            mcUsers = mdDatabase.GetCollection(Of Trebuchet.User)("Users")

            uUser = New Trebuchet.User

            uUser.Email = objFacebookUser.email 'TODO: Email does not come back, need to retrieve,
            uUser.FacebookID = objFacebookUser.id

            mcUsers.Save(uUser)

            uNewUser = uUser
            CreateUserFromFacebook = True

        Catch ex As Exception

            CreateUserFromFacebook = False

        End Try

    End Function

    Private Sub UpdateUserFromFacebook(ByVal objFacebookUser As Object)

    End Sub
End Class